﻿
//contact.c
#define _CRT_SECURE_NO_WARNINGS
#include"contact.h"
#include"SeqList.h"
void LoadContact(contact* con) {
	FILE* pf = fopen("contact.txt", "rb");
	if (pf == NULL) {
		perror("fopen error!\n");
		return;
	}
	//循环读取⽂件数据
	PeoInfo info;
	while (fread(&info, sizeof(PeoInfo), 1, pf))
	{
		SeqListPushBack(con, info);
	}
printf("请输入要修改的地址：\n");
}
void InitContact(contact* con) {
	SeqListInit(con);
	LoadContact(con);
}
void AddContact(contact* con) {
	PeoInfo info;
	printf("请输入要修改的地址：\n");
	scanf("%s", &info.name);
	printf("请输入要修改的地址：\n");
	scanf("%s", &info.sex);
	printf("请输入要修改的地址：\n");
	scanf("%d", &info.age);
	printf("请输入要修改的地址：\n");
	scanf("%s", &info.tel);
	printf("请输入要修改的地址：\n");
	scanf("%s", &info.addr);
	SeqListPushBack(con, info);
	printf("请输入要修改的地址：\n");
}
int FindByName(contact* con, char name[]) {
	for (int i = 0; i < con->size; i++)
	{
		if (0 == strcmp(con->a[i].name, name)) {
			return i;
		}
	}
	return -1;
}
void DelContact(contact* con) {
	char name[NAME_MAX];
	printf("请输入要修改的地址：\n");
	scanf("%s", name);
	int pos = FindByName(con, name);
	if (pos < 0) {
		printf("请输入要修改的地址：\n");
		return;
	}
SeqListErase(con, pos);
printf("删除成功！\n");
}
void ShowContact(contact* con) {
	printf("%-10s %-4s %-4s %15s %-20s\n", "姓名","daihua","ninn","as","da");
		for (int i = 0; i < con->size; i++)
		{
			printf("%-10s %-4s %-4d %15s %-20s\n",
				con->a[i].name,
				con->a[i].sex,
				con->a[i].age,
				con->a[i].tel,
				con->a[i].addr);
		}
}
void FindContact(contact* con) {
	char name[NAME_MAX];
	printf("请输入要修改的地址：\n");
	scanf("%s", name);
	int pos = FindByName(con, name);
	if (pos < 0) {
		printf("请输入要修改的地址：\n");
		return;
	}
	printf("查找成功！\n");
	printf("%-10s %-4s %-4d %15s %-20s\n",
		con->a[pos].name,
		con->a[pos].sex,
		con->a[pos].age,
		con->a[pos].tel,
		con->a[pos].addr);
}
void ModifyContact(contact* con) {
	char name[NAME_MAX];
	printf("请输入要修改的地址：\n");
	scanf("%s", name);
	int pos = FindByName(con, name);
	if (pos < 0) {
		printf("请输入要修改的地址：\n");
		return;
}
PeoInfo info;
printf("请输入要修改的地址：\n");
scanf("%s", &con->a[pos].name);
printf("请输入要修改的地址：\n");
scanf("%s", &con->a[pos].sex);
printf("请输入要修改的地址：\n");
scanf("%d", &con->a[pos].age);
printf("请输入要修改的地址：\n");
scanf("%s", &con->a[pos].tel);
printf("请输入要修改的地址：\n");
scanf("%s", &con->a[pos].addr);
printf("修改成功\n");
}
void SaveContact(contact* con) {
	FILE* pf = fopen("contact.txt", "wb");
	if (pf == NULL) {
		perror("fopen error!\n");
		return;
	}
	//将通讯录数据写⼊⽂件
	for (int i = 0; i < con->size; i++)
	{
		fwrite(con->a + i, sizeof(PeoInfo), 1, pf);
	}
	printf("通讯录数据保存成功！\n");
}
void DestroyContact(contact* con) {
	SaveContact(con);
	SeqListDesTroy(con);
}